<script setup>
import { reactive, ref, onMounted, computed } from 'vue'
import { useExpenseProjectList, useOwnerHouseList, useCommunityNameList } from '@/hooks/detail.js'
import Table from '@/components/Form/table'
import Pagination from '@/components/Form/Pagination'
import { getDetailListAPI, addDetailAPI, getDetailInfoAPI, editDetailAPI, delDetailAPI } from '@/api/expenses'
import { buildingListApi } from "@/api/hooks";
import { ElMessage } from 'element-plus';


const communityList = useCommunityNameList()
const expenseProjectList = useExpenseProjectList()
const ownerHouseList = useOwnerHouseList()

// 列表查询参数
const queryData = reactive({
  current: 1,
  pageSize: 6,
  community_code: '',
  project_code: '',
  house_code: '',
  create_time: ''
})
// 渲染列表
const list = ref([])
const total = ref(0)
const initData = async () => {
  const { data: { count, rows } } = await getDetailListAPI(queryData)
  console.log({ data: { count, rows } })
  list.value = rows
  total.value = count
}
onMounted(() => {
  initData()
})
const detailTable = [
  { value: 'id', label: 'ID' },
  { value: 'community.name', label: '小区名称' },
  { value: 'expenses_project.name', label: '收费项目' },
  { value: 'house.name', label: '房产信息' },
  { value: 'amount_total', label: '应收金额' },
  { value: 'amount_paid', label: '实收金额' },
  { value: 'remark', label: '备注' },
  { value: 'create_time', label: '创建时间' }
]
// 控制抽屉开关变量
const drawer = ref(false)
// 表单数据
const formData = reactive({
  amount_paid: '',
  amount_total: '',
  building_code: '',
  community_code: '',
  house_code: '',
  project_code: '',
  remark: ''
})
// 表单校验
const formRules = {
  community_code: [{ required: true, message: "请选择", trigger: "change" }],
  project_code: [{ required: true, message: "请选择", trigger: "change" }],
  amount_total: [{ required: true, message: "请输入", trigger: "blur" }],
  amount_paid: [{ required: true, message: "请输入", trigger: "blur" }],
}
// 标题事件
const title = computed(() => {
  return formData.id ? '修改收费明细' : '新增收费明细'
})
// 表单引用
const formRef = ref()


//小区改变获取楼栋
const BuildingList = ref([])
const changeBuildingList = async (val) => {
  formData.building_code = ''
  formData.house_code = ''
  console.log(val);
  let { data } = await buildingListApi(val)
  BuildingList.value = data
  // console.log(data);

}


// 表单提交
const onSubmit = async () => {
  try {
    // 表单校验
    await formRef.value.validate()
    // 处理数据
    formData.remark = formData.remark !== '' ? formData.remark : '用户未备注'
    const data = toRaw(formData)
    // 发送请求
    formData.id ? await editDetailAPI(data) : await addDetailAPI(data)
    // 提示成功
    ElMessage.success('操作成功')
    // 关闭弹框
    drawer.value = false
    // 移除校验
    await formRef.value.resetFields()
    // 更新列表
    initData()
  } catch (error) {
    console.log(error)
  }
}
// 抽屉关闭之前
const handleClose = () => {
  // 移除校验
  formRef.value.resetFields()
  // 重置表单
  Object.assign(formData, {
    amount_paid: '',
    amount_total: '',
    building_code: '',
    community_code: '',
    house_code: '',
    project_code: ''
  })
  drawer.value = false
}
// 数据回显
const replyData = async (id) => {
  let { data } = await getDetailInfoAPI(id)
  console.log(data)
  Object.assign(formData, data)
  drawer.value = true
}
// 修改事件
const edit = (id) => {
  replyData(id)
}
// 删除事件
const del = async (id) => {
  // 发送请求
  await delDetailAPI(id)
  // 提示成功
  ElMessage.success('删除成功')
  // 边缘问题
  if (queryData.pageNum > 1 && list.value.length === 1) queryData.pageNum--
  initData()
}
// 查询
const onSearch = () => {
  // queryData.pageNum=1
  queryData.create_time = queryData.create_time !== '' ? queryData.create_time.map(item => +item).join(',') : queryData.create_time
  initData()
}
// 重置
const onReset = () => {
  Object.assign(queryData, {
    current: 1,
    pageSize: 6,
    community_code: '',
    project_code: '',
    house_code: '',
    create_time: ''
  })
  initData()
}
</script>

<template>
  <div>
    <el-card>
      <b>收费明细管理</b> <b style="font-weight: 400;font-size:12px;">用于展示物业收费明细列表信息，以及增加、修改、删除等操作</b>
      <el-card>
        <!-- 搜索区域 -->
        <el-form label-width="70px" :inline="true" size="normal">
          <el-row :gutter="20">
            <el-col :span="5" :offset="0">
              <el-form-item label="小区名称">
                <el-select placeholder="请输入" v-model="queryData.community_code">
                  <el-option v-for="item in communityList" :key="item.id" :label="item.name"
                    :value="item.code"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="0">
              <el-form-item label="收费项目">
                <el-select placeholder="请选择" v-model="queryData.project_code">
                  <el-option v-for="item in expenseProjectList" :key="item.id" :label="item.name" :value="item.code"
                    placeholder="请选择"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5" :offset="0">
              <el-form-item label="房产信息">
                <el-select placeholder="请选择" v-model="queryData.house_code">
                  <el-option v-for="item in ownerHouseList" :key="item.id" :label="item.name" :value="item.code"
                    placeholder="请选择"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="9" :offset="0">
              <el-form-item label="创建时间">
                <el-date-picker v-model="queryData.create_time" type="daterange" range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期" style="width:250px">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="19"></el-col>
            <el-col :span="5" :offset="0">
              <el-form-item>
                <el-button type="primary" @click="onSearch">查询</el-button>
                <el-button @click="onReset">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <br>
      <el-card>
        <!-- 工具区域 -->
        <el-row type="flex" justify="space-between">
          <div></div>
          <div>
            <el-button type="primary" @click="drawer = true">新增明细</el-button>
          </div>
        </el-row>
        <br>
        <!-- 表格区域 -->
        <Table :table="detailTable" :tableData="list" @edit="edit" @del="del">
          <template #community.name="{ row }">{{ row.community?.name }}</template>
          <template #expenses_project.name="{ row }">{{ row.expenses_project?.name }}</template>
          <template #house.name="{ row }">{{ row.building?.name }}栋{{ row.house?.name }} 【{{ row.house?.owner_name
          }}】</template>
          <template #create_time="{ row }">{{ new Date(row.create_time).toLocaleString() }}</template>
        </Table>

        <!-- 分页区域 -->
        <Pagination v-model:pageNum="queryData.current" v-model:pageSize="queryData.pageSize" :total="total"
          @initData="initData" />

        <!-- 新增修改抽屉 -->
        <el-drawer size="50%" v-model="drawer" direction="rtl" :title="title" :before-close="handleClose">
          <!-- 绘制一个表单内容 -->
          <el-form :model="formData" ref="formRef" :rules="formRules" label-width="80px">

            <el-form-item label="所属小区" prop="community_code">
              <el-select v-model="formData.community_code" style="width: 50%" @change="changeBuildingList">
                <el-option v-for="item in communityList" :key="item.id" :label="item.name" :value="item.code"
                  placeholder="请选择"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="收费项目" prop="project_code">
              <el-select v-model="formData.project_code" style="width: 50%">
                <el-option v-for="item in expenseProjectList" :key="item.id" :label="item.name" :value="item.code"
                  placeholder="请选择"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="所述楼栋" prop="building_code">
              <el-select v-model="formData.building_code" style="width: 50%">
                <el-option v-for="item in BuildingList" :key="item.id" :label="item.name" :value="item.code"
                  placeholder="请选择"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="所属房产" prop="house_code">
              <el-select v-model="formData.house_code" style="width: 50%">
                <el-option v-for="item in ownerHouseList" :key="item.id" :label="item.name" :value="item.code"
                  placeholder="请选择"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="应收金额" prop="amount_total">
              <el-input style="width: 50%" v-model="formData.amount_total" placeholder="请输入"></el-input>
            </el-form-item>

            <el-form-item label="实收金额" prop="amount_paid">
              <el-input style="width: 50%" v-model="formData.amount_paid" placeholder="请输入"></el-input>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" style="width: 50%" v-model="formData.remark"
                placeholder="如果不是房产的收费信息，则记录在这里"></el-input>
            </el-form-item>

            <el-form-item>
              <el-button size="small" type="primary" @click="onSubmit">确定</el-button>
              <el-button size="small" @click="handleClose">取消</el-button>
            </el-form-item>

          </el-form>
        </el-drawer>

      </el-card>
    </el-card>
  </div>
</template>

<style scoped></style>
